package com.grapevine.contact.util;

import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.grapevine.contact.data.ContactData;
import com.grapevine.contact.data.ItemData;
import com.grapevine.contact.db.TypeManager;

public class JSONUtil
{

	public static JSONObject createJson(List<ContactData> list)
	{
		JSONObject jo = new JSONObject();
		JSONArray data = new JSONArray();
		put(jo, "action", "commit");
		put(jo, "model", "contacts");
		put(jo, "count", list.size());

		for (ContactData d : list)
		{
			data.put(createJson(d));
		}
		put(jo, "data", data);
		return jo;
	}

	public static JSONObject createJson(ContactData data)
	{
		JSONObject jo = new JSONObject();
		put(jo, "name", data.getName());
		put(jo, "guuid", data.getGuuid());
		put(jo, "uuid", data.getUuid());
		List<ItemData> list = data.getItemDatas();
		if (list.size() > 0)
		{
			JSONArray jArray = new JSONArray();
			for (ItemData item : list)
			{
				JSONObject oj = new JSONObject();
				JSONObject ext = new JSONObject();

				put(oj, "lable", item.getLable());

				put(oj, "uuid", item.getUuid());

				put(ext, "t", item.getType());

				put(ext, "ft", item.getFatherType());

				if (item.getFatherType() == TypeManager.ORGANIZATION)
				{
					try
					{
						JSONObject oo = new JSONObject(item.getValue());
						String value = getString(oo, "company") + "  ";
						value += getString(oo, "job");
						put(oj, "value", value);
						put(ext, "d", item.getValue());
					}
					catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
				else if (item.getFatherType() == TypeManager.ADDRESS)
				{
					try
					{
						JSONObject ao = new JSONObject(item.getValue());
						String value = getString(ao, "region") + "  ";
						value += getString(ao, "city") + "  ";
						value += getString(ao, "street") + "  ";
						value += getString(ao, "postcode");
						put(oj, "value", value);
						put(ext, "d", item.getValue());
					}
					catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
				else
				{
					put(oj, "value", item.getValue());
				}
				put(oj, "ext", ext);
				jArray.put(oj);
			}
			put(jo, "infor", jArray);
		}

		return jo;
	}

	public static void put(JSONObject jo, String key, Object value)
	{
		try
		{
			jo.put(key, value);
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
	}

	public static String getString(JSONObject jo, String key)
	{
		try
		{
			return jo.getString(key);
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
		return "";
	}

}